package com.example.cloudinterviewdemo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author liuwanxu
 * @date 2025/8/28 14:38
 */
@RestController
public class MemoryStressController {
    private List<Object> memoryHog = new ArrayList<>();

    /**
     * 模拟堆内存溢出
     * @param elementsToAdd 每次调用添加多少MB的数据（约）
     */
    @GetMapping("/memory/heap")
    public String stressHeap(@RequestParam(defaultValue = "10") int elementsToAdd) {
        // 每次调用大约添加 elementsToAdd MB 的数据
        for (int i = 0; i < elementsToAdd; i++) {
            // 创建一个约1MB大小的对象（假设一个字符2字节，1MB ≈ 500,000个字符）
            StringBuilder largeString = new StringBuilder();
            for (int j = 0; j < 500000; j++) {
                largeString.append(UUID.randomUUID().toString());
            }
            // 将大对象添加到静态集合中，防止被GC回收
            memoryHog.add(largeString.toString());
        }
        return "Added ~" + elementsToAdd + " MB to the heap. Total held: " + memoryHog.size() + " MB.";
    }

    /**
     * 释放持有的内存
     */
    @GetMapping("/memory/release")
    public String releaseMemory() {
        int size = memoryHog.size();
        memoryHog.clear();
        // 建议主动触发GC（注意：这只是个建议，JVM不保证立即执行）
        System.gc();
        return "Released " + size + " MB of memory.";
    }
}
